package com.lituoxy.dialer.thread;

import com.lituoxy.dialer.DialerApplication;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 作者：许航晨 on 2017/7/11 15:14
 * 邮箱：948340983@qq.com
 */

public class GetTokenThread implements Runnable {
    @Override
    public void run() {
        String token = getTokey();
        if (token == null) {
            try {
                Thread.sleep(3000);
                token = getTokey();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            ((DialerApplication) DialerApplication.getContext()).setToKey(token);
        }
    }

    public String getTokey() {
        String access_token = null;
        RequestBody formBody = new FormBody.Builder()
                .add("key", "kjasdhfgk34rt89790yhiklsdhnf897867vnnnn")
                .build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://120.25.227.239:8060/accesstoken/get2").post(formBody)
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                JSONObject object = new JSONObject(json);
                String info = object.getString("info");
                if ("成功".equals(info)) {//成功
                    object = object.getJSONObject("data");
                    access_token = object.getString("access_token");
                }

            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return access_token;
    }
}
